﻿using System;
using System.Windows.Forms;
using System.Xml;
using PluginInterface;
using SdmxMl.Common;
using SdmxMl.GenericMetadata;
using SdmxMl.Manager;
using SdmxMl.Structure;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using Telerik.WinControls.UI.Export;

namespace SmsUsers
{
    public partial class UcSmsClients : UserControl, IPlugin
    {
        #region Internal members

        private bool InEdition;
        private MetadataSetType metadataSet;
        private GridCreator gridCreator;
        private static string GroupFullId = "CH1_SMS+CL_SMS_GROUP+1.0";
        private static string MetaSetFullId = "CH1_SMS+GMD_SMS_UGRP+1.0";

        #endregion

        #region Constructor

        public UcSmsClients()
        {
            InitializeComponent();

            SetEditionState(false);
        }
        #endregion

        #region Set menu items state

        private void SetEditionState(bool editable)
        {
            bool isAdministrator = SdmxMl.Multiplexor.Mux.Instance.UserIsAdmin;
            radMenuButtonEdit.Enabled = isAdministrator;
            radMenuButtonEdit.Text = "&Edit SMS Users";

            if (isAdministrator == false)
                editable = false;

            radMenuItemAddUser.Enabled = editable;
            radMenuItemAddGroup.Enabled = editable;
            InEdition = editable;
            radGrid1.ReadOnly = editable == false;
            ledBulb.On = false;
        }
        #endregion

        #region Application closing Event

        void TreeMgr_AppliClosing(object sender, EventArgs e)
        {
            if (InEdition && ledBulb.On)
                radMenuButtonEdit_Click(this, EventArgs.Empty);
        }
        #endregion

        #region Control Load Event

        /// <summary> Control Load Event, fetch users info and prepare grid content </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void UcSmsClients_Load(object sender, EventArgs e)
        {
            try
            {
                ReferenceManager.TreeMgr.AppliClosing += new EventHandler(TreeMgr_AppliClosing);

                gridCreator = new GridCreator(radGrid1);

                LoadSmsUsersInGrid();

                radMenuComboItemGroup.Items.Add("All Groups");
                foreach (CodeType c in gridCreator.cltCodeGroup.CodeList)
                    radMenuComboItemGroup.Items.Add(c.Id);
                
                radMenuComboItemGroup.ComboBoxElement.SelectedIndex = 0;
                radMenuComboItemGroup.ComboBoxElement.SelectedIndexChanged += new Telerik.WinControls.UI.Data.PositionChangedEventHandler(ComboBoxElement_SelectedIndexChanged);

                SetEditionState(false);
            }
            catch (Exception ex)
            {
                RadMessageBox.Show(this, ex.Message, "I/O Error", MessageBoxButtons.OK, RadMessageIcon.Error);
            }
        }

        void ComboBoxElement_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            // Set visible only rows of selected group          
            gridCreator.SetGroupVisibility(GetSelectedGroup());
        }

        private string GetSelectedGroup()
        {
            bool allGroups = radMenuComboItemGroup.ComboBoxElement.SelectedIndex <= 0;
            return radMenuComboItemGroup.ComboBoxElement.SelectedIndex <= 0 ?
                string.Empty : radMenuComboItemGroup.ComboBoxElement.SelectedItem.ToString();
        }

        #endregion

        #region Load Data

        private void LoadSmsUsersInGrid()
        {
            using (new SdmxMl.Helper.CWaitCursor())
            {
                SmManager sm = new SmManager();
                ArtefactRefTyped art = new ArtefactRefTyped(SdmxArtefactType.MetadataSet, MetaSetFullId);
                MetadataSetType mSet = sm.GetArtefact(art.Type, art, true) as MetadataSetType;
                CodeListType cltGroup = sm.GetArtefact(SdmxArtefactType.CodeLists, new ArtefactRefBase(GroupFullId), true) as CodeListType;
                if (cltGroup == null)
                    throw new ApplicationException("Unable to fetch group codelist");

                gridCreator.SetView(true, mSet, cltGroup, GetSelectedGroup());
            }
        }
        #endregion

        #region IPlugin Members

        /// <summary>Event is part of interface but not used </summary>
        public event PluginEvent PluginEventExposed
        {
            add { }
            remove { }
        }

        public void Init(System.Xml.XmlDocument xDoc, object obExtend)
        {

        }

        public UserControl VisualComponent()
        {
            return this;
        }

        public bool RequiresInit
        {
            get { return false; }
        }

        #endregion

        #region Save and Publish

        private void radMenuButtonEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (InEdition)
                {
                    radMenu1.Select();
                    if (ledBulb.On &&
                        MessageBox.Show("Save SMS Users edited content ? ", "SMS Users", 
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        SaveSmsUsersInRegistry();
                    }
                    else
                    {
                        SdmxMl.Multiplexor.Mux.Instance.UndoCheckOut(SdmxArtefactType.MetadataSet.ToString(), MetaSetFullId);
                        // reload
                        LoadSmsUsersInGrid();
                    }

                    SetEditionState(false);
                }
                else
                {
                    // check out
                    SdmxMl.Multiplexor.Mux.Instance.CheckOut(SdmxArtefactType.MetadataSet.ToString(), MetaSetFullId);

                    // reload
                    LoadSmsUsersInGrid();
                    SetEditionState(true);
                    radMenuButtonEdit.Text = "Save and publish";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void SaveSmsUsersInRegistry()
        {
            using (new SdmxMl.Helper.CWaitCursor())
            {
                radGrid1.CancelEdit();

                // Update in registry
                metadataSet = gridCreator.FillMetaset();
                SdmxMl.Multiplexor.Mux.Instance.CheckOut(SdmxArtefactType.MetadataSet.ToString(), metadataSet.FullIdent);
                SmManager sm = new SmManager();
                sm.PutArtefact(SdmxArtefactType.MetadataSet, metadataSet);
                XmlDocument xDoc = sm.GetMetasetAsDocument(metadataSet.FullIdent);
                SdmxMl.Multiplexor.Mux.Instance.SubmitArtefact(SdmxArtefactType.MetadataSet.ToString(), metadataSet.FullIdent, xDoc);


                SdmxMl.Multiplexor.Mux.CreateNewInstance();
                SdmxMl.Multiplexor.Mux.Instance.DistributeOrgScheme();
            }
        }

        
        #endregion

        #region Content changed Events

        private void radGrid1_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            if (InEdition)
                ledBulb.On = true;
        }

        private void radGrid1_RowsChanged(object sender, GridViewCollectionChangedEventArgs e)
        {
            if (InEdition)
                ledBulb.On = true;
        }
        #endregion

        #region Excel Export

        private void radMenuItem2_Click(object sender, EventArgs e)
        {
            RunExportToExcelML();
        }

        private void RunExportToExcelML()
        {
            
            ExportToExcelML excelExporter = new ExportToExcelML(this.radGrid1);

            excelExporter.SummariesExportOption = SummariesOption.ExportAll;
            //set export settings
            excelExporter.ExportVisualSettings = false;
            excelExporter.ExportHierarchy = true;
            excelExporter.HiddenColumnOption = HiddenOption.DoNotExport;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                saveFileDialog.Filter = "Excel (*.xls)|*.xls";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    excelExporter.RunExport(saveFileDialog.FileName);

                    DialogResult dr = RadMessageBox.Show("The data in the grid was exported successfully. Do you want to open the file?",
                        "Export to Excel", MessageBoxButtons.YesNo, RadMessageIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveFileDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                RadMessageBox.SetThemeName(this.radGrid1.ThemeName);
                RadMessageBox.Show(this, ex.Message, "I/O Error", MessageBoxButtons.OK, RadMessageIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Add user

        private void radMenuItemAddUser_Click(object sender, EventArgs e)
        {
            DlgNewUser aDlg = new DlgNewUser(gridCreator.cltCodeGroup);
            if (aDlg.ShowDialog() == DialogResult.OK)
            {
                if (gridCreator.ExistUser(aDlg.UserId))
                {
                    RadMessageBox.SetThemeName(this.radGrid1.ThemeName);
                    RadMessageBox.Show(this, "User already exists: " + aDlg.UserId, "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
                }
                else
                    gridCreator.AddUser(aDlg.UserId, aDlg.UserName, aDlg.UserMail, aDlg.UserGroup, aDlg.IsGroupAdmin);
            }
        }
        #endregion

        #region Add Group

        private void radMenuItemAddGroup_Click(object sender, EventArgs e)
        {
            DlgAddGroup aDlg = new DlgAddGroup(GroupFullId, gridCreator.cltCodeGroup);
           
            if (aDlg.ShowDialog() == DialogResult.OK)
            {
                gridCreator.RefreshGroups(aDlg.cltGroup);
            }
        }

        #endregion

    }
}

    

